﻿using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace xycn.framework.Common
{
    /// <summary>
    /// 将字符串转换为指定类型的对象
    /// 注:仅能转换为简单的类型，如int、string、bool等
    /// </summary>
    public static class String2ObjectOfSpecific
    {
        /// <summary>
        /// 将字符串格式化成指定的数据类型
        /// </summary>
        /// <param name="str">输入字符串</param>
        /// <param name="type">转化为指定类型</param>
        /// <param name="converted_obj">输出转化的object</param>
        /// <param name="err_msg">输出转化出错信息</param>
        /// <returns>0，成功；-1，失败</returns>
        public static int Convert(string str, Type type,
            out Object converted_obj, out string err_msg)
        {
            converted_obj = null;
            err_msg = "";
            if (String.IsNullOrEmpty(str))
                return -1;

            if (type == null)
            {
                converted_obj = str;
                return 0;
            }

            int ret = 0;
            //转化数组
            if (type.IsArray)
            {
                Type elementType = type.GetElementType();
                String[] strs = str.Split(new char[] { ';' });
                Array array = Array.CreateInstance(elementType, strs.Length);
                for (int i = 0, c = strs.Length; i < c; ++i)
                {
                    Object tp_obj;
                    if (ConvertSimpleType(strs[i], elementType, out tp_obj, out err_msg) < 0)
                    {
                        ret = -1;
                        break;
                    }
                    array.SetValue(tp_obj, i);
                }
                if (ret == 0)
                {
                    converted_obj = array;
                }
                return ret;
            }

            //转化简单类型
            ret = ConvertSimpleType(str, type, out converted_obj, out err_msg);
            return ret;
        }

        /// <summary>
        /// 反射转化简单类型
        /// </summary>
        /// <param name="value"></param>
        /// <param name="destinationType"></param>
        /// <param name="converted_obj"></param>
        /// <param name="err_msg"></param>
        /// <returns></returns>
        private static int ConvertSimpleType(object value, Type destinationType,
            out Object converted_obj, out string err_msg)
        {
            converted_obj = null;
            err_msg = "";
            if ((value == null) || destinationType.IsInstanceOfType(value))
            {
                converted_obj = value;
                return 0;
            }

            string str = value as string;
            if ((str != null) && (str.Length == 0))
            {
                converted_obj = null;
                return 0;
            }

            int ret = 0;

            TypeConverter converter = TypeDescriptor.GetConverter(destinationType);
            bool flag = converter.CanConvertFrom(value.GetType());
            if (!flag)
            {
                converter = TypeDescriptor.GetConverter(value.GetType());
            }
            if (!flag && !converter.CanConvertTo(destinationType))
            {
                err_msg = "无法转换成类型：" + value.ToString() + "==>" + destinationType + "。";
                return -1;
            }

            try
            {
                converted_obj = flag ? converter.ConvertFrom(null, null, value) : converter.ConvertTo(null, null, value, destinationType);
            }
            catch (Exception e)
            {
                err_msg = "类型转换出错：" + value.ToString() + "==>" + destinationType + "。" + e.Message;
                return -1;
            }

            return 0;
        }
    }
}
